<?php
namespace app\user_api\controller;

use tp5_lib\api\controller\ApiBaseController;
use tp5_lib\user\model\UserModel;
use app\user\validate\UserValidate;
use tp5_lib\user\logic\UserLogic;
use tp5_lib\user\model\MobileCodeModel;
use tp5_lib\aliyun\utility\Sms;

/**
 * 用户相关的接口
 * @property UserModel $model 用户模型
 * @property UserLogic $logic 用户逻辑
 * @property UserValidate $validate 用户验证器
 */
class LoginController extends ApiBaseController
{
    public function __get($name)
    {
        if($name === "model"){
            if(empty($this->_model)){
                $this->_model=new UserModel();
            }
            return $this->_model;
        }
        elseif($name === "logic"){
            if(empty($this->_logic)){
                $this->_logic=new UserLogic();
            }
            return $this->_logic;
        }
        elseif($name === "validate"){
            if(empty($this->_validate)){
                $this->_validate=new UserValidate();
            }
            return $this->_validate;
        }
    }
    /**
     * 注册用户
     */
    public function register()
    {
        $data=input();
        if(!$this->validate->scene("register")->check($data)){
            $this->error($this->validate->getError());
        }
        $user=$this->logic->register($data["username"],$data["password"],$data);
        if(!$user){
            $this->error($this->logic->getError());
        }
        $this->result($user,1);
    }
    /**
     * 登录
     */
    public function login()
    {
        $data=input();
        if(!$this->validate->scene("login")->check($data)){
            $this->error($this->validate->getError());
        }
        $user=$this->logic->login($data["username"],$data["password"]);
        if(!$user){
            $this->error($this->logic->getError());
        }
        $this->result($user,1);
    }
    /**
     * 找回密码
     */
    public function getbackPassword()
    {
        $data=input();
        if(!$this->validate->scene("getback_password")->check($data)){
            $this->error($this->validate->getError());
        }
        if(!$this->logic->getback($data["username"],$data["code"],$data["new_password"])){
            $this->error($this->logic->getError());
        }
        $this->success();
    }
    public function sendSmsCode()
    {
        if(!$mobile=input("mobile")) $this->error("手机号不能为空");
        if(!$method=input("method")) $this->error("方法名不能为空");

        if($method === "register"){
            if(UserModel::where(["mobile"=>$mobile])->find()) $this->error("手机号已被占用");
        }
        elseif(in_array($method, ["login","bind","findback"])){
            
        }
        else{
            $this->error("未定义的方法");
        }

        $mcm=new MobileCodeModel;
        $result=$mcm->send($mobile,$method);
        if(!$result){
            $this->error($mcm->getError());
        }
        Sms::instance()->sendVerifyCode($mobile,$result["code"]);
        $this->success("发送成功,手机号:$mobile");
    }
}
